package com.htu.controller;

import com.htu.po.IdWorker;
import com.htu.po.Result;
import com.htu.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private AliPayService aliPayService;

    @RequestMapping("/createNative")
    public Map createNative(String total_fee) {
        IdWorker idWorker = new IdWorker();
        long nextId = idWorker.nextId();
        System.out.println(nextId);
        return aliPayService.createNative(nextId+ "", total_fee);
    }

    @RequestMapping("/queryPayStatus")
    public Result queryPayStatus(String out_trade_no) {
        Result result = null;
        while (true) {
            Map<String, String> map = null;
            map = aliPayService.queryPayStatus(out_trade_no);
            if (map == null) {
                result = new Result(false, "支付出错了");
                break;
            }
            if (map.get("tradestatus") != null && map.get("tradestatus").equals("TRADE_SUCCESS")) {
                result = new Result(true, "支付成功");
                break;
            }

            if (map.get("tradestatus") != null && map.get("tradestatus").equals("TRADE_CLOSED")) {
                result = new Result(true, "未付款交易超时，或支付完成全额退款");
                break;
            }
            if (map.get("tradestatus") != null && map.get("tradestatus").equals("TRADE_FINISHED")) {
                result = new Result(true, "交易结束，不可退款");
                break;
            }
//            if (map.get("tradestatus") != null && map.get("tradestatus").equals("WAIT_BUYER_PAY")) {
//                result = new Result(true, "下单成功，等待支付");
//                break;
//            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("result:"+result);
        }
        return result;

    }

}

